package com.snow.useviewdemo.util

import android.content.Context
import androidx.datastore.DataStore
import androidx.datastore.preferences.*
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.launch

/**
 * Created by zhyt
 * Date: 2022/9/26
 * Describe:
 */
class PreferencesDataStoreUtils private constructor() {
    companion object {
        @Volatile
        private var INSTANCE: PreferencesDataStoreUtils? = null
        fun getInstance(): PreferencesDataStoreUtils {
            return INSTANCE ?: synchronized(this) {
                INSTANCE?.let { return it }
                val instance = PreferencesDataStoreUtils()
                INSTANCE = instance
                instance
            }
        }
    }

    private val USER_PREFERENCES_NAME: String = "user"
    private lateinit var dataStore: DataStore<Preferences>
    fun init(context: Context) {
        //创建新的user
        dataStore = context.createDataStore(name = "user")
        //迁移SharedPreferences存储数据
        //注意：系统仅会将键值从 SharedPreferences 中迁移一次，因此一旦将代码迁移到 DataStore，就应该停止使用旧的 SharedPreferences。
//        dataStore = context.createDataStore(
//            name = USER_PREFERENCES_NAME,
//            migrations = listOf(SharedPreferencesMigration(context, USER_PREFERENCES_NAME))
//        )
    }

    /**
     *  CoroutineScope(Dispatchers.IO).launch {}
     *
     *  GlobalScope.launch(Dispatchers.IO) {}
     */
    suspend fun getString(key: String): String {
        val nameFlow: Flow<String> = dataStore.data
            .map { preferences ->
                preferences[preferencesKey<String>(key)] ?: ""
            }
        return nameFlow.first()
    }

    suspend fun putString(key: String, value: String) {
        dataStore.edit { preferences ->
            preferences[preferencesKey<String>(key)] = value
        }
    }

}